import localforage from "localforage";
import { max, merge } from "lodash";

var store = localforage.createInstance({
  name: "order"
});

interface Data extends Record<string, any> {
  // id: string
}

async function add(data: Data) {
  const keys = await store.keys()
  // const lastKey = keys.at(-1)
  const lastKey = max(keys.map(Number))
  // console.log({ lastKey });
  const key = String(Number(lastKey || 0) + 1)
  await store.setItem(key, data)
  return { id: key, ...data }
}

async function del(id: string) {
  return store.removeItem(id)
}

async function update(data: Data) {
  const { id, ...restData } = data
  const oldData = await store.getItem<Data>(id)
  const newData = merge(oldData, restData)
  return store.setItem(id, newData)
}

async function get(id: string) {
  return store.getItem(id)
}

async function list() {
  const allList: any[] = []
  await store.iterate((value: any, key, iterationNumber) => {
    allList.push({ id: key, ...value })
  })
  return allList
}

export const orderStore = { add, del, update, get, list }